package main

import (
	"fmt"
	"strings"
)

// 地鼠装配线
func main() {
	downstream := make(chan string)
	upstream := make(chan string)
	go sourceGopher(downstream)
	go filterGopher(downstream, upstream)
	printGopher(upstream)
}

// 流水线源头，向通道发送值
func sourceGopher(downstream chan string) {
	for _, v := range []string{"hello world", "a bad apple", "goodbye all"} {
		// 向 downstream 发送值
		downstream <- v
	}
	// 发送空值 用作 哨兵值，作为发送完毕的标识
	downstream <- ""
}

// 中间流水线，用作筛选的
func filterGopher(upstream, downstream chan string) {
	for {
		// 从 upstream 取值
		v := <-upstream
		// 若发送完毕了
		if v == "" {
			downstream <- ""
			return
		}
		// 筛选出来符合条件的值
		if !strings.Contains(v, "bad") {
			// 向 downstream 发送值
			downstream <- v
		}
	}
}

// 打印
func printGopher(upstream chan string) {
	// 遍历通道 取值
	for {
		// 从 upstream 取值
		v := <-upstream
		// 若发送完毕了
		if v == "" {
			return
		}
		fmt.Println(v)
	}

}
